package com.quanyan.place.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.quanyan.common.constants.Constants;
import com.quanyan.place.entity.*;
import com.quanyan.place.mapper.TbBizPlaceCategoryMapper;
import com.quanyan.place.thread.ModifyPlaceSalePlanBundleThread;
import com.quanyan.place.utils.PlaceUtil;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.apireq.ReqPlaceBundle;
import com.quanyan.place.entity.apiresp.RespPlaceBundleVo;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.mapper.TbBizPlaceAttachMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMainMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMapper;
import com.quanyan.place.service.PlaceBundleSaleService;
import com.quanyan.place.utils.PlaceOrderUtil;

/**
 * Created by youxiaojia on 2016/10/12.
 */
@Service("placeBundleSaleService")
public class PlaceBundleSaleServiceImpl implements PlaceBundleSaleService{
    private static final Logger logger = LoggerFactory.getLogger(PlaceBundleSaleServiceImpl.class);
    @Autowired
    private TbBizPlaceAttachMapper tbBizPlaceAttachMapper;

    @Autowired
    private TbBizPlaceUnitSalePlanMainMapper tbBizPlaceUnitSalePlanMainMapper;

    @Autowired
    private TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;

    private static ExecutorService updatePlaceUnitBundleNoExecutorService = Executors.newSingleThreadExecutor();
    /**
     * 返回场馆销售时段
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getPlaceSaleTimes(Integer placeId, Integer categoryId) {
        //获取场馆附属信息
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = example.createCriteria();
        tbBizPlaceAttachCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);
        String startTime = null;
        String endTime = null;
        Byte minSaleTimeUnit = Constants.BYTE_ONE;
        if (null != categoryId){
            TbBizPlaceCategory placeCategory = this.getPlaceCategory(placeId, categoryId);
            minSaleTimeUnit = placeCategory.getMinSaleTimeUnit();
        }
        int intervalTime = PlaceUtil.getTimeInterval(minSaleTimeUnit);

        if (CollectionUtils.isNotEmpty(result)) {
            TbBizPlaceAttach tbBizPlaceAttach = result.get(0);
            /*if (tbBizPlaceAttach.getBusinessHourStart().compareTo(tbBizPlaceAttach.getHolidayBusinessHourStart()) >= 0) {
                startTime = tbBizPlaceAttach.getHolidayBusinessHourStart();
            } else {
                startTime = tbBizPlaceAttach.getBusinessHourStart();
            }

            if (tbBizPlaceAttach.getBusinessHourEnd().compareTo(tbBizPlaceAttach.getHolidayBusinessHourEnd()) >= 0) {
                endTime = tbBizPlaceAttach.getBusinessHourEnd();
            } else {
                endTime = tbBizPlaceAttach.getHolidayBusinessHourEnd();
            }*/
            startTime = tbBizPlaceAttach.getBusinessHourStart();
            endTime = tbBizPlaceAttach.getBusinessHourEnd();
        } else {
            logger.debug("该场馆没有可用的销售时段！");
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnSuccess(PlaceOrderUtil.getIntervalTimeList(startTime, endTime, intervalTime));
    }

    /**
     * 获取捆绑销售时段规则
     * @param placeId
     * @param categoryId
     * @return
     */
    @Override
    public APIResponse getBundleSale(Integer placeId, Integer categoryId) {
        TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample1 = new TbBizPlaceUnitSalePlanMainExample();
        TbBizPlaceUnitSalePlanMainExample.Criteria tbBizPlaceUnitSalePlanMainCriteria1 = tbBizPlaceUnitSalePlanMainExample1.createCriteria();
        tbBizPlaceUnitSalePlanMainCriteria1.andPlaceIdEqualTo(placeId);
        tbBizPlaceUnitSalePlanMainCriteria1.andCategoryIdEqualTo(categoryId);
        tbBizPlaceUnitSalePlanMainCriteria1.andIsEffectiveEqualTo(PlaceConstants.YES);
        tbBizPlaceUnitSalePlanMainCriteria1.andBundleNoIsNotNull();
        tbBizPlaceUnitSalePlanMainCriteria1.andBundleNoNotEqualTo(0);
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainList = tbBizPlaceUnitSalePlanMainMapper.selectByExample(tbBizPlaceUnitSalePlanMainExample1);

        if (!CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMainList)){
            List<RespPlaceBundleVo> respPlaceBundleVoList = new ArrayList<>();
            for (TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain : tbBizPlaceUnitSalePlanMainList){
                /*if(!bundleSaleData.containsKey(tbBizPlaceUnitSalePlanMain.getTimeType())) {//不存在相同的绑定号
                    Map<String,List<RespPlaceBundleTime>> bundleNoMap = new HashMap<>();
                    bundleSaleData.put(tbBizPlaceUnitSalePlanMain.getTimeType().toString(),bundleNoMap);
                }
                if (!bundleSaleData.get(tbBizPlaceUnitSalePlanMain.getTimeType().toString()).containsKey(tbBizPlaceUnitSalePlanMain.getTimeType() + tbBizPlaceUnitSalePlanMain.getBundleNo())){
                    List<RespPlaceBundleTime> respPlaceBundleTimes = new ArrayList<>();
                    bundleSaleData.get( tbBizPlaceUnitSalePlanMain.getTimeType().toString()).put(tbBizPlaceUnitSalePlanMain.getTimeType() +tbBizPlaceUnitSalePlanMain.getBundleNo().toString(),respPlaceBundleTimes);
                }*/
                RespPlaceBundleVo respPlaceBundleVo = new RespPlaceBundleVo();
                respPlaceBundleVo.setWeek(tbBizPlaceUnitSalePlanMain.getTimeType());
                respPlaceBundleVo.setStartTime(DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceUnitSalePlanMain.getStartTime()));
                respPlaceBundleVo.setEndTime(DateTimeUtils.convertDate2String("HH:mm:ss",tbBizPlaceUnitSalePlanMain.getEndTime()));
                respPlaceBundleVo.setBundle_no(tbBizPlaceUnitSalePlanMain.getBundleNo());
                respPlaceBundleVoList.add(respPlaceBundleVo);
            }
            return APIResponse.returnSuccess(respPlaceBundleVoList);
        } else {
            TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample2 = new TbBizPlaceUnitSalePlanMainExample();
            TbBizPlaceUnitSalePlanMainExample.Criteria tbBizPlaceUnitSalePlanMainCriteria2 = tbBizPlaceUnitSalePlanMainExample2.createCriteria();
            tbBizPlaceUnitSalePlanMainCriteria2.andPlaceIdEqualTo(placeId);
            tbBizPlaceUnitSalePlanMainCriteria2.andCategoryIdEqualTo(categoryId);
            tbBizPlaceUnitSalePlanMainCriteria2.andIsEffectiveEqualTo(PlaceConstants.YES);
            List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMains = tbBizPlaceUnitSalePlanMainMapper.selectByExample(tbBizPlaceUnitSalePlanMainExample2);
            if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMains)){
                return APIResponse.returnSuccess(PlaceErrorCodeEnum.BUNDLE_NOT_PRICE_ERROR);
            }
        }
        return APIResponse.returnSuccess(null);
    }

    /**
     * 设置捆绑销售
     * @param reqPlaceBundle
     * @return
     */
    @Override
    public APIResponse settingBundleSale(ReqPlaceBundle reqPlaceBundle) {
        TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
        TbBizPlaceUnitSalePlanMainExample.Criteria tbBizPlaceUnitSalePlanMainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
        tbBizPlaceUnitSalePlanMainCriteria.andBundleNoIsNotNull();
        tbBizPlaceUnitSalePlanMainExample.setOrderByClause("bundle_no desc");
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainList = tbBizPlaceUnitSalePlanMainMapper.selectByExample(tbBizPlaceUnitSalePlanMainExample);
        Integer maxBundleNo = 0;
        if (!CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMainList)){
            maxBundleNo = tbBizPlaceUnitSalePlanMainList.get(0).getBundleNo();
        }
        Map<String,List<Map<String,String>>> bundleSaleData = reqPlaceBundle.getBundleSaleData();
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainListAll = new ArrayList<>();
        List<String> notPirceTbBizPlaceUnitSalePlanMainList = new ArrayList<>();
        int flag = 0;
        for (Map.Entry<String, List<Map<String,String>>> entryAll : bundleSaleData.entrySet()) {
            //entry.getKey() 周几
            //entry.getValue() 当天开始时间，结束时间list
            System.out.println("all -- key= " + entryAll.getKey() + " and value= " + JSON.toJSON(entryAll.getValue()));
            for (Map<String,String> timeList : entryAll.getValue()){
                maxBundleNo++;
                for (Map.Entry<String, String> entryTime : timeList.entrySet()){

                    System.out.println("day -- key= " + entryTime.getKey() + " and value= " + JSON.toJSON(entryTime.getValue())+" maxNo ="+maxBundleNo);
                    TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample1 = new TbBizPlaceUnitSalePlanMainExample();
                    TbBizPlaceUnitSalePlanMainExample.Criteria tbBizPlaceUnitSalePlanMainCriteria1 = tbBizPlaceUnitSalePlanMainExample1.createCriteria();
                    tbBizPlaceUnitSalePlanMainCriteria1.andPlaceIdEqualTo(reqPlaceBundle.getPlaceId());
                    tbBizPlaceUnitSalePlanMainCriteria1.andCategoryIdEqualTo(reqPlaceBundle.getCategoryId());
                    tbBizPlaceUnitSalePlanMainCriteria1.andTimeTypeEqualTo(entryAll.getKey());
                    tbBizPlaceUnitSalePlanMainCriteria1.andStartTimeEqualTo(DateTimeUtils.convertString2Date("HH:mm:ss", entryTime.getKey()));
                    tbBizPlaceUnitSalePlanMainCriteria1.andIsEffectiveEqualTo(PlaceConstants.YES);
                    tbBizPlaceUnitSalePlanMainCriteria1.andEndTimeEqualTo(DateTimeUtils.convertString2Date("HH:mm:ss", entryTime.getValue()));
                    TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
                    tbBizPlaceUnitSalePlanMain.setBundleNo(maxBundleNo);
                    tbBizPlaceUnitSalePlanMain.setUpdateUid(reqPlaceBundle.getUid());
                    flag = flag + tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain,tbBizPlaceUnitSalePlanMainExample1);
                    List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainList1 = tbBizPlaceUnitSalePlanMainMapper.selectByExample(tbBizPlaceUnitSalePlanMainExample1);
                    tbBizPlaceUnitSalePlanMainListAll.addAll(tbBizPlaceUnitSalePlanMainList1);
                    if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMainList1)){
                        notPirceTbBizPlaceUnitSalePlanMainList.add(entryTime.getKey()+" - "+entryTime.getValue());
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanMainListAll)){
            updatePlaceUnitBundleNoExecutorService.execute(new ModifyPlaceSalePlanBundleThread(tbBizPlaceUnitSalePlanMainListAll,tbBizPlaceUnitSalePlanMapper,null));//null设置捆绑
        }
        logger.debug("-- 捆绑"+flag+"个销售模板 --");
        if (flag > 1){
            return APIResponse.returnSuccess(notPirceTbBizPlaceUnitSalePlanMainList);
        } else {
            //return APIResponse.returnFail("至少选择两个或两个以上已定价的时段捆绑！");
            return APIResponse.returnSuccess(notPirceTbBizPlaceUnitSalePlanMainList);
        }
    }

    /**
     * 取消捆绑销售
     * @param bundleNo
     * @return
     */
    @Override
    public APIResponse cancelBundleSale(Integer bundleNo) {
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainListAll = new ArrayList<>();
        int flag = 0;
        TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample1 = new TbBizPlaceUnitSalePlanMainExample();
        TbBizPlaceUnitSalePlanMainExample.Criteria tbBizPlaceUnitSalePlanMainCriteria1 = tbBizPlaceUnitSalePlanMainExample1.createCriteria();
        tbBizPlaceUnitSalePlanMainCriteria1.andBundleNoEqualTo(bundleNo);
        TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
        tbBizPlaceUnitSalePlanMain.setBundleNo(0);
        List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainList1 = tbBizPlaceUnitSalePlanMainMapper.selectByExample(tbBizPlaceUnitSalePlanMainExample1);
        flag = flag + tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain,tbBizPlaceUnitSalePlanMainExample1);
        tbBizPlaceUnitSalePlanMainListAll.addAll(tbBizPlaceUnitSalePlanMainList1);
        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanMainListAll)){
            updatePlaceUnitBundleNoExecutorService.execute(new ModifyPlaceSalePlanBundleThread(tbBizPlaceUnitSalePlanMainListAll,tbBizPlaceUnitSalePlanMapper,0));//0取消捆绑
        }
        logger.debug("-- 取消捆绑"+flag+"个销售模板 --");
        if (flag>0){
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("取消捆绑失败");
    }

    /**
     * 根据场馆id和运动项目查询场馆项目配置
     * @param placeId
     * @param categoryId
     * @return
     */
    public TbBizPlaceCategory getPlaceCategory(Integer placeId, Integer categoryId) {
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        tbBizPlaceCategoryCriteria.andCategoryIdEqualTo(categoryId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList = tbBizPlaceCategoryMapper.selectByExample(tbBizPlaceCategoryExample);
        if (null != tbBizPlaceCategoryList && tbBizPlaceCategoryList.size() > 0){
            return tbBizPlaceCategoryList.get(0);
        }
        return null;
    }

}
